package com.cabd.utils;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.nio.charset.Charset;
import java.util.ArrayList;

import com.cabd.staticfinal.DownLoadAndUpLoadPath;
import com.csvreader.CsvReader;
import com.csvreader.CsvWriter;

public class CSVUtils {
	public static ArrayList<String> getValue(String path, Integer begin, Integer end){
		if(end < begin) {
			return new ArrayList<String>();
		}
		ArrayList<String> arrayList = new ArrayList<>();
		try {
			CsvReader csvReader = new CsvReader(path,',',Charset.forName("GBK"));
			int j = -2;
			while(j < begin) {
				csvReader.skipRecord();
				j++;
			}
			while(j < end) {
				String tempValue = csvReader.getRawRecord();
				arrayList.add(tempValue);
				csvReader.skipRecord();
				j++;
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
		return arrayList;
	}
	public static int getRecordNumber(String path) {
		CsvReader csvReader = null;
		int count = 0;
		try {
			csvReader = new CsvReader(path, ',' , Charset.forName("GBK"));
			try {
				while(csvReader.readRecord()) {
					count++;
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		}
		return count;
	}
	
	public static void changeHeaders(String folderName) throws IOException{
		//处理航班信息的csv文件
		String pathWrite = DownLoadAndUpLoadPath.downLoadAndUpLoadPath+"\\"+
							folderName+"\\flight_information_temp.csv";
		String pathRead = DownLoadAndUpLoadPath.downLoadAndUpLoadPath+"\\"+
							folderName+"\\flight_information.csv";
		CsvWriter csvWriter = new CsvWriter(pathWrite, ',', Charset.forName("GBK"));
		CsvReader csvReader = new CsvReader(pathRead, ',', Charset.forName("GBK"));
		String []records = {"出发机场","到达机场","航班编号","计划起飞时间","计划到达时间",
				"实际起飞时间","实际到达时间","飞机编号","航班是否取消","需验证标识（1为需提交结果、0不需要提交）"};
		csvWriter.writeRecord(records);
		csvReader.readHeaders();
		while(csvReader.readRecord()){
			String []arg = csvReader.getRawRecord().split(",");
			for(String eString:arg)
				System.out.print(eString + "  ");
			System.out.println();
			csvWriter.writeRecord(arg);
		}
		csvReader.close();
		csvWriter.close();
		File tempFile = new File(pathRead);
		tempFile.delete();
		File newFile = new File(pathWrite);
		newFile.renameTo(new File(pathRead));
	}
}
